<template>
  <el-dialog
    :model-value="modelValue"
    @update:model-value="$emit('update:modelValue', $event)"
    :title="isEdit ? '编辑工单' : '创建工单'"
    width="600px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      size="default"
    >
      <el-form-item label="工单标题" prop="title">
        <el-input
          v-model="formData.title"
          placeholder="请输入工单标题"
          maxlength="100"
          show-word-limit
        />
      </el-form-item>
      
      <el-form-item label="优先级" prop="priority">
        <el-select v-model="formData.priority" placeholder="请选择优先级" style="width: 100%;">
          <el-option label="高" value="high" />
          <el-option label="中" value="medium" />
          <el-option label="低" value="low" />
        </el-select>
      </el-form-item>
      
      <el-form-item label="分配用户" prop="assigneeId">
        <el-select v-model="formData.assigneeId" placeholder="请选择分配用户" style="width: 100%;" clearable>
          <el-option
            v-for="user in userList"
            :key="user.id"
            :label="user.name"
            :value="user.id"
          />
        </el-select>
      </el-form-item>
      
      <el-form-item label="SLA截止时间" prop="slaDeadline">
        <el-date-picker
          v-model="formData.slaDeadline"
          type="datetime"
          placeholder="选择SLA截止时间"
          style="width: 100%;"
          :disabled-date="disabledDate"
        />
      </el-form-item>
      
      <el-form-item label="紧急标记">
        <el-switch
          v-model="formData.isUrgent"
          active-text="紧急"
          inactive-text="普通"
        />
      </el-form-item>
      
      <el-form-item label="工单描述" prop="description">
        <el-input
          v-model="formData.description"
          type="textarea"
          :rows="4"
          placeholder="请详细描述工单内容..."
          maxlength="500"
          show-word-limit
        />
      </el-form-item>
    </el-form>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          {{ isEdit ? '更新' : '创建' }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch, nextTick } from 'vue'
import { ElMessage } from 'element-plus'

// Props
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  ticket: {
    type: Object,
    default: null
  },
  userList: {
    type: Array,
    default: () => []
  }
})

// Emits
const emit = defineEmits(['update:modelValue', 'success'])

console.log('工单对话框组件加载')

// 响应式数据
const formRef = ref()
const submitting = ref(false)

// 表单数据
const formData = ref({
  title: '',
  priority: 'medium',
  assigneeId: null,
  slaDeadline: null,
  isUrgent: false,
  description: ''
})

// 表单验证规则
const formRules = {
  title: [
    { required: true, message: '请输入工单标题', trigger: 'blur' },
    { min: 5, max: 100, message: '标题长度应在 5 到 100 个字符', trigger: 'blur' }
  ],
  priority: [
    { required: true, message: '请选择优先级', trigger: 'change' }
  ],
  slaDeadline: [
    { required: true, message: '请选择SLA截止时间', trigger: 'change' }
  ],
  description: [
    { required: true, message: '请输入工单描述', trigger: 'blur' },
    { min: 10, max: 500, message: '描述长度应在 10 到 500 个字符', trigger: 'blur' }
  ]
}

// 计算属性
const isEdit = computed(() => {
  return props.ticket && props.ticket.id
})

// 监听对话框显示状态
watch(() => props.modelValue, (newVal) => {
  if (newVal) {
    initFormData()
  } else {
    resetForm()
  }
})

// 监听工单数据变化
watch(() => props.ticket, (newVal) => {
  if (newVal && props.modelValue) {
    initFormData()
  }
})

// 初始化表单数据
const initFormData = () => {
  console.log('初始化表单数据', props.ticket)
  
  if (props.ticket) {
    // 编辑模式
    formData.value = {
      title: props.ticket.title || '',
      priority: props.ticket.priority || 'medium',
      assigneeId: props.ticket.assignee?.id || null,
      slaDeadline: props.ticket.slaDeadline ? new Date(props.ticket.slaDeadline) : null,
      isUrgent: props.ticket.isUrgent || false,
      description: props.ticket.description || ''
    }
  } else {
    // 创建模式
    const now = new Date()
    const defaultDeadline = new Date(now.getTime() + 24 * 60 * 60 * 1000) // 默认24小时后
    
    formData.value = {
      title: '',
      priority: 'medium',
      assigneeId: null,
      slaDeadline: defaultDeadline,
      isUrgent: false,
      description: ''
    }
  }
  
  // 清除验证状态
  nextTick(() => {
    if (formRef.value) {
      formRef.value.clearValidate()
    }
  })
}

// 重置表单
const resetForm = () => {
  console.log('重置表单')
  
  formData.value = {
    title: '',
    priority: 'medium',
    assigneeId: null,
    slaDeadline: null,
    isUrgent: false,
    description: ''
  }
  
  if (formRef.value) {
    formRef.value.clearValidate()
  }
}

// 禁用过去的日期
const disabledDate = (time) => {
  return time.getTime() < Date.now() - 24 * 60 * 60 * 1000
}

// 取消操作
const handleCancel = () => {
  console.log('取消工单操作')
  emit('update:modelValue', false)
}

// 提交表单
const handleSubmit = async () => {
  console.log('提交工单表单')
  
  if (!formRef.value) return
  
  try {
    // 表单验证
    await formRef.value.validate()
    
    submitting.value = true
    
    // 构建提交数据
    const submitData = {
      ...formData.value,
      slaDeadline: formData.value.slaDeadline?.toISOString(),
      assignee: formData.value.assigneeId ? 
        props.userList.find(user => user.id === formData.value.assigneeId) : null
    }
    
    // 如果是编辑模式，保留原有ID和其他字段
    if (isEdit.value) {
      submitData.id = props.ticket.id
      submitData.status = props.ticket.status
      submitData.createdAt = props.ticket.createdAt
    } else {
      submitData.status = 'pending'
      submitData.createdAt = new Date().toISOString()
    }
    
    console.log('提交数据:', submitData)
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 发送成功事件
    emit('success', submitData)
    
    ElMessage.success(isEdit.value ? '工单更新成功' : '工单创建成功')
    
  } catch (error) {
    console.error('表单验证失败:', error)
    ElMessage.error('请检查表单输入')
  } finally {
    submitting.value = false
  }
}
</script>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #374151;
}

:deep(.el-input__wrapper) {
  border-radius: 6px;
}

:deep(.el-select .el-input__wrapper) {
  border-radius: 6px;
}

:deep(.el-textarea__inner) {
  border-radius: 6px;
}

:deep(.el-date-editor.el-input) {
  border-radius: 6px;
}
</style>
